package pl.smath.regex;

import java.util.Vector;

public class PatternBuilder {

	/**
	 * We do not allow nested optional/alternative expressions.
	 */
	private void findOptions(String read, String parse, Vector<String> collect) {
		int from = parse.indexOf('[');
		if (from == -1) { 
			collect.add(read + parse);
			return;
		}
		int to = parse.indexOf(']');
		int pile = parse.indexOf('|');
		if (from < pile && pile < to) { // alternative
			String divide = parse.substring(from + 1, to);
			for (String inside : divide.split("\\|")) {
				findOptions(read + parse.substring(0, from) + inside, parse.substring(to + 1), collect);
			}
		} else { // option
			findOptions(read + parse.substring(0, from), parse.substring(to + 1), collect);
			findOptions(read + parse.substring(0, from) + parse.substring(from + 1, to), parse.substring(to + 1), collect);
		}
		return;
	}
	
	private String fixSumRanges(String toCompile) {
		int pos = toCompile.indexOf("Sum");
		
		while(pos != -1) {
			int end = toCompile.indexOf("}", pos);
			toCompile = toCompile.substring(0,pos) + toCompile.substring(pos, end).replaceAll("=", ":") + toCompile.substring(end); 
			end = toCompile.indexOf("}", pos);
			pos = toCompile.indexOf("Sum", end);
		}
		
		return toCompile;
	}
	
	public Pattern compile(String toCompile) {

		toCompile = toCompile.replaceAll("[ \t\r\n\f]", "");
		toCompile = fixSumRanges(toCompile);
				
		Vector<String> options = new Vector<String>();
		findOptions("", toCompile, options);

		return new Pattern(options);
	}


	
	
}
